<template>
  <div class="formContainer">
    <el-card header="Lucas有限公司后台管理系统">
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        label-position="left"
      >
        <el-form-item label="用户名" prop="name">
          <el-input
            type="text"
            v-model="ruleForm.name"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="ruleForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >提交</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { login } from "../api/admins";
import { SetToken } from "../utils/auth";

export default {
  data() {
    return {
      ruleForm: {
        name: "",
        password: "",
      },
      rules: {
        name: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          login(this.ruleForm)
            .then((data) => {
              let res = data;
              console.log(res);
              //判断账号密码正确
              if (res.code === 1000 && res.data.admin.isActived === true) {
                 // localStorage.setItem("accessToken", data.data.token);
                 // localStorage.setItem("refreshToken", data.data.refreshToken);
                localStorage.setItem("name", res.data.admin.name);
                SetToken(res.data.token, res.data.refreshToken);
                this.$message({ type: "success", message: res.msg });
                this.$router.push("/");
              } else {
                this.$message({ type: "error", message: res.msg });
              }
            })
            .catch((err) => {
              console.log(err);
              this.$message({ type: "error", message: err });
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style>
/* 卡片宽度 */
.el-card__body {
  width: 400px;
}

/* 整个大容器居中 */
.formContainer {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  /* background-image: url("../assets/14.jpg"); */
  background-color: pink;
}

/* 背景框虚化 */
.el-card {
  opacity: 0.7;
}
</style>